import 'package:get/get.dart';
import 'package:situation/app/router/router_name.dart';
import 'package:situation/data/request/communication_request.dart';
import 'package:situation/domain/chat/concat_list_domain.dart';
import 'package:situation/domain/chat/conversation_msg.dart';
import 'package:tdesign_flutter/src/components/cell/td_cell.dart';
import 'package:wukongimfluttersdk/entity/conversation.dart';
import 'package:wukongimfluttersdk/type/const.dart';
import 'package:wukongimfluttersdk/wkim.dart';

import 'state.dart';

class CommunicationConcatListController extends GetxController {
  final CommunicationConcatListState state = CommunicationConcatListState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    // _initListener();
    initData();
  }



  void initData() async {
    state.orgList = await CommunicationRequest.getAddressBookList();
    update();
    _getDataList();
    _initListener();
  }
  void _getDataList() {
    Future<List<WKUIConversationMsg>> list =
    WKIM.shared.conversationManager.getAll();

    list.then((result) {
      for (var i = 0; i < result.length; i++) {
        state.msgPut[result[i].channelID] = UIConversation(result[i]);
      }
    });

    // 1秒后执行
    Future.delayed(Duration(seconds: 1), () {
      update();
    });
  }


  _initListener() {
    // 监听连接状态事件

    WKIM.shared.conversationManager
        .addOnClearAllRedDotListener("chat_conversation", () {
      for (var i = 0; i < state.msgList.length; i++) {
        state.msgList[i].msg.unreadCount = 0;
      }
    });

    // 列表中监听到
    WKIM.shared.conversationManager
        .addOnRefreshMsgListListener('chat_conversation', (msgs) async {
      if (msgs.isEmpty) {
        return;
      }
      for (WKUIConversationMsg msg in msgs) {
        state.msgPut[msg.channelID] = UIConversation(msg);
        update();
      }
    });

    // 监听刷新channel资料事件
    WKIM.shared.channelManager.addOnRefreshListener("cover_chat", (channel) {
      for (var i = 0; i < state.msgList.length; i++) {
        if (state.msgList[i].msg.channelID == channel.channelID &&
            state.msgList[i].msg.channelType == channel.channelType) {
          state.msgList[i].msg.setWkChannel(channel);
          state.msgList[i].channelAvatar = "";
          state.msgList[i].channelName = channel.channelName;
          break;
        }
      }
    });
  }

  void onTap(OrgChildItem e) {
    Get.toNamed(RouterName.communicationChat,arguments: {
      "remoteId": e.gwsdId,
      "remoteName": e.gwsdUsername,
      "remoteHeadImgUrl": e.headImgUrl,
      "name": e.name,
      "idcard": e.id
    });
  }
}
